var fs = require('fs.extra');
var path = require('path');
var ndir = require('ndir');
var officegen = require('officegen');
var zip = require("node-native-zip");


var ejs = require('ejs');
/*
 * GET home page.
 */

exports.index = function(req, res){
  res.redirect('/index.html');
};

exports.build = function(req, res) {
//  res.send(req.body.report);
  var report = req.body.report = JSON.parse(req.body.report);
  res.header('Content-Disposition','attachment; filename="report.zip"');
  res.header('ContentType','application/octet-stream');
  function makeDocx(r) {
    var docx = officegen ( 'docx' );
    docx.on ( 'finalize', function ( written ) {
      console.log ( 'Finish to create Word file.\nTotal bytes created: ' + written + '\n' );
    });

    docx.on ( 'error', function ( err ) {
      console.log ( err );
    });
    var pObj = docx.createP ( { align: 'center'} );
    pObj.addText ( r.title ,{bold: true,font_face:"宋体",font_size: 15} );

//    var pObj = docx.createP ( { align: 'center'} );
//    pObj.addText ( r.date ,{bold: true,font_face:"宋体",font_size: 14} );

    r.content.forEach(function(e,i){
       switch(e.type){
         case "sub-title":
           var pObj = docx.createP();
           pObj.addText (e.data,{bold: true,font_face:"宋体",font_size: 14} );
           break;
         case "text":
           var paras = e.data.split('\n');
           paras.forEach(function(para){
             var pObj = docx.createP();
             pObj.addText ( '    '+ para,  {font_face:"宋体",font_size: 14} );
           });
           break;
         case "pic":
           var pObj = docx.createP ({align:"center"});
           pObj.addImage ( path.resolve(__dirname, '../public/images/'+ e.data ),{cx:"400",cy:"400",x:"c"} );
           break;
         case "pic-desc":
           var pObj = docx.createP ({align:"center"});
           pObj.addText (e.data,{bold: true,font_face:"宋体",font_size: 12} );
           break;
         case "empty":
           docx.createP();
           break;
         default :
           break;
       }
    });

    return docx;
  }

  fs.readFile('./views/demo.ejs', 'utf8', function (err, data) {
    if (err) throw err;
    var html = ejs.render(data,{"report":req.body.report});//html

    var docx = makeDocx(report);
    var filename = Date.now() + '_tmp.docx';
    var out = fs.createWriteStream( path.resolve(__dirname, '../tmp/'+filename ));

    docx.generate ( out,{
      'error': function ( err ) {
        console.log ( err );
      },
      'finalize': function ( written ) {
        var files = [];
        report.content.forEach(function(e,i){
          if(e.type == "pic"){
            files.push({
              name:'report/images/'+ e.data,
              path:'./public/images/'+ e.data
            });
          }
        });
        files.push({
          name:'report/report.docx',
          path:'./tmp/'+filename
        });
        console.log ( 'Finish to create a PowerPoint file.\nTotal bytes created: ' + written + '\n' );
        var archive = new zip();
        archive.add("report/index.html", new Buffer(html, "utf8"));
        archive.addFiles(files,function (err) {
          if (err) return console.log("err while adding files", err);

          var buff = archive.toBuffer();

          res.send(buff);
          fs.remove('./tmp/'+filename,function(err){
            if(err){
              console.log(err);
            }
          });
        });
      }
    });
  });

}



exports.uploadImage = function (req, res, next) {

  var file = req.files && req.files.file;
  if (!file) {
    res.send({ status: 'failed', message: 'no file' });
    return;
  }
  var userDir = path.join(path.join(__dirname,"..","public","images"));
  ndir.mkdir(userDir, function (err) {
    if (err) {
      return next(err);
    }
    var filename = Date.now() + '_' + file.name;
    var savepath = path.resolve(path.join(userDir, filename));
    if (savepath.indexOf(path.resolve(userDir)) !== 0) {
      return res.send({status: 'forbidden'});
    }
    fs.move(file.path, savepath, function (err) {
      if (err) {
        return next(err);
      }
      var url = '/public/images/' + encodeURIComponent(filename);
      res.send({ status: 'success', url: url ,name : filename});
    });
  });
};
